package com.love.cloud.auth.service.impl;


import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.love.cloud.admin.api.dto.UserInfo;
import com.love.cloud.admin.api.entity.SysUser;
import com.love.cloud.auth.service.LoginAttemptService;
import com.love.cloud.common.core.constant.CacheConstants;
import com.love.cloud.common.core.constant.CommonConstants;
import com.love.cloud.common.core.constant.SecurityConstants;
import com.love.cloud.common.security.service.MyUser;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * @author hongdongqu
 */
public abstract class BaseUserDetailServiceImpl implements UserDetailsService {
    @Resource
    private CacheManager cacheManager;
    @Resource
    private LoginAttemptService loginAttemptService;

    @Override
    public UserDetails loadUserByUsername(String var1) throws UsernameNotFoundException {
        //判断是否为登陆次数失败超限
        if(!loginAttemptService.isLocked(var1)){
            throw new InvalidGrantException("登陆失败超过5次,该账号给锁定10分钟");
        }

        Cache cache = cacheManager.getCache(CacheConstants.USER_DETAILS);
        if (cache != null && cache.get(var1) != null) {
            return (MyUser) cache.get(var1).get();
        }
        UserInfo result = getUser(var1);
        UserDetails userDetails = getUserDetails(result);
        if (cache != null) {
            cache.put(var1, userDetails);
        }
        return userDetails;
    }
    protected abstract UserInfo getUser(String var1) ;

    /**
     * 构建userdetails
     * @param info 用户信息
     * @return
     */
    protected UserDetails getUserDetails(UserInfo info) {
        if (info == null ) {
            throw new UsernameNotFoundException("用户不存在");
        }
        Set<String> dbAuthsSet = new HashSet<>();
        if (ArrayUtil.isNotEmpty(info.getRoles())) {
            // 获取角色
            info.getRoles().forEach(role -> dbAuthsSet.add(SecurityConstants.ROLE + role.getRoleId()));
            // 获取资源
            dbAuthsSet.addAll(Arrays.asList(info.getPermissions()));

        }
        Collection<? extends GrantedAuthority> authorities = AuthorityUtils
                .createAuthorityList(dbAuthsSet.toArray(new String[0]));
        SysUser user = info.getSysUser();

        // 构造security用户
        return new MyUser(user.getId(), info.getSysDeptList(), user.getUsername(),
                SecurityConstants.BCRYPT + user.getPassword(),
                StrUtil.equals(user.getStatus(), CommonConstants.STATUS_NORMAL), true, true, true, authorities,info);
    }
}
